﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Silvermoon.Classes
{
    public class FormThreads : IDisposable
    {
        private LinkedList<Thread> threads = new LinkedList<Thread>();

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            ExitAll();
        }

        ~FormThreads()
        {
            Dispose();
        }

        public void ExitAll()
        {
            lock (threads)
            {
                foreach (Thread t in threads)
                {
                    t.Abort();
                }
                threads.Clear();
            }
        }

        public void Enqueue(ThreadStart t)
        {
            ThreadPool.QueueUserWorkItem((o) =>
                {
                    QueueThread();
                    t();
                    DequeueThread();
                });
        }

        public void Enqueue(WaitCallback callback, object obj)
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                QueueThread();
                callback(o);
                DequeueThread();
            }, obj);
        }


        private void DequeueThread()
        {
            Thread t = Thread.CurrentThread;
            lock (threads)
            {
                threads.Remove(t);
            }
        }

        private void QueueThread()
        {
            Thread t = Thread.CurrentThread;
            if (t.Priority > ThreadPriority.Lowest) t.Priority--;
            Thread.Sleep(0);
            lock (threads)
            {
                threads.AddLast(t);
            }
        }
    }
}
